onlineMusic.controller('player_server', ['$scope', '$http',
    function ($scope, $http) {
    
    $scope.playlist;
    $scope.current_id;
    
    setInterval( function() { 
        $scope.checkPlaylist();
    } , 2000);
    
    var a = audiojs.createAll({
        trackEnded: function() {
            
            $http.get('api/playlist').success(function(data) {                
                for(i = 0; i < data.length; i++){
                    if(data[i].current_played == 1){
                        if(data.length == ($scope.current_id+1)){
                            $scope.current_id = 0;
                            $scope.playSong(data[$scope.current_id].song_id);
                        } else {
                            $scope.current_id = $scope.current_id+1;
                            $scope.playSong(data[$scope.current_id].song_id);
                        }
                    }
                }
            });
        },
        loadError: function(){
            document.location.reload();
        }
    });

    var base_player = a[0];
    
    $http.get('api/playlist').success(function(data) {
        $scope.playlist = data;
        for(i = 0; i < data.length; i++){
            if(data[i].current_played == 1){
                $scope.current_id = i;
                $scope.playSong(data[i].song_id);
            }
        }
    });    
    
    $scope.playSong = function(id){
        $scope.search_inprogress = true;
        $http.get('api/stream/'+id).success(function(data) {
            base_player.load(data);
            base_player.play();
            $scope.setPlaying(id);
        });   
    }
    
    $scope.setPlaying = function(id){
        $http.get('api/played/'+id).success(function(data){
            $scope.updatePlaylist();
        }); 
    }
    
    $scope.updatePlaylist = function(){
        $http.get('api/playlist').success(function(data) {
            $scope.playlist = data;
        });  
    }
    
    $scope.checkPlaylist = function(){
        $http.get('api/playlist').success(function(data) {
            for(i = 0; i < data.length; i++){
                if(data[i].current_played == 1){
                   if(data[i].change_track == 5){
                        $http.get('api/changed/'+data[i].song_id);
                        if(data.length == ($scope.current_id+1)){
                            $scope.current_id = 0;
                            $scope.playSong(data[$scope.current_id].song_id);
                        } else {
                            $scope.current_id = $scope.current_id+1;
                            $scope.playSong(data[$scope.current_id].song_id);
                        }
                   }
                   
                }
            }
        });  
    }
    
}]);